<template>
  <Layout class="menu-left">
    <Menu mode="horizontal" @on-select='lowerStep' :active-name="modaleshow">
      <MenuItem :name="1">设备设施风险</MenuItem>
      <MenuItem :name="2">作业流程风险</MenuItem>
      <MenuItem :name="3">人员岗位风险</MenuItem>
      <MenuItem :name="4">环境氛围风险</MenuItem>
    </Menu>
    <Form ref="form1" :model="form1" :label-width="120">
      <Row class="query-form" style="padding-top: 10px" v-show="!switchFlag">
        <Col span="8">
          <FormItem label="风险类别：">
            <Select filterable v-model="form1.riskType"
                    :label-in-value="true">
              <Option v-for="item in riskTypeArr" :value="item.codingCodeId" :label="item.codingName">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="风险识别维度：">
            <!--    <Input type="text" v-model="form1.rikDiscernName"/>-->
            <Select v-model="form1.rikDiscernName">
              <Option v-for="item in rikDiscernList" :value="item.codingCodeId" :label="item.codingName">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>

        <Col span="8">
          <Button @click="switchQuery(true)" class="ivu-btn-switch" type="text">展开∨</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query()">查询</Button>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form" style="padding-top: 10px">
        <Col span="8">
          <FormItem label="风险类别：">
            <Select filterable v-model="form1.riskType"
                    :label-in-value="true">
              <Option v-for="item in riskTypeArr" :value="item.codingCodeId" :label="item.codingName">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>

        <Col span="8">
          <FormItem label="风险识别维度：">
            <!--  <Input type="text" v-model="form1.rikDiscernName"/>-->
            <Select v-model="form1.rikDiscernName">
              <Option v-for="item in rikDiscernList" :value="item.codingCodeId" :label="item.codingName">
                {{ item.codingName }}
              </Option>
            </Select>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="风险等级：">
            <!-- <Input type="text" v-model="form1.rikRankId"/>-->
            <Select v-model="rikRanks" multiple style="width:100%">
              <Option v-for="item in rikRankList" :value="item" :key="item">{{ item }}</Option>
            </Select>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8">
          <FormItem label="一级风险单元：">
            <Input type="text" v-model="form1.riskUnit"/>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级风险单元：">
            <Input type="text" v-model="form1.riskUnit2"/>
          </FormItem>
        </Col>

        <Col span="8">
          <FormItem label="三级风险单元：">
            <Input type="text" v-model="form1.riskUnit3"/>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">

        <Col span="8">
          <FormItem label="四级风险单元：">
            <Input type="text" v-model="form1.riskUnit4"/>
          </FormItem>
        </Col>

        <Col span="8">
          <FormItem label="录入时间：">
            <DatePicker type="year" :clearable="false" v-model='form1.date' style="width: 100%"></DatePicker>
          </FormItem>
        </Col>
        <Col span="8">
          <FormItem label="二级集团：">
            <two-level-org org-code class="w" v-model="form1.twoLevelOrgId"></two-level-org>
          </FormItem>
        </Col>
      </Row>
      <Row v-show="switchFlag" class="query-form">
        <Col span="8" offset="16">
          <Button @click="switchQuery(false)" class="ivu-btn-switch" type="text">收起∧</Button>
          <Button @click="reset" class="ivu-btn-reset">重置</Button>
          <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
        </Col>
      </Row>
    </Form>
    <Row class="query-form">
      <Col span="24">
        <Button type="primary" class="ivu-btn-add" icon="md-cloud-download" @click="downloadFile"
                :loading="loadingDownload">导出
        </Button>
<!--        <Button size="large" :disabled="reportSelectAll.length<1" :loading="buttonLoading"
                class="ivu-btn-add" icon="md-remove-circle" @click="reporting">
          退回
        </Button>-->
      </Col>

    </Row>
    <Table ref='table' :loading="loading" size="small" :height="tableHeight" class="no-add-table"
           no-data-text="没有查询到相关数据!" highlight-row stripe border :columns="columns1" width="100%"
           :data="dataTable">
    </Table>
    <Row style="margin-right:10px;">
      <Col span="24">
        <Page :total="pagedata.total" :page-size="pagedata.pageSize" @on-change="pageChange"
              style="float: right" @on-page-size-change="pageSizeChange" :page-size-opts="pageSizeArray"
              show-total show-sizer show-elevator/>
      </Col>
    </Row>

    <Modal :transfer=false v-model="model1" :width=1000>
      <p slot="header">
        <span v-if="modaleshow==1">设备设施风险</span>
        <span v-else-if="modaleshow==2">作业流程风险</span>
        <span v-else-if="modaleshow==3">人员岗位风险</span>
        <span v-else>环境氛围风险</span>
      </p>
      <Form :model="InputData" label-position="top">
        <div v-if="modaleshow==1">
          <equipmentFacilitiesRiskApproval ref="equipmentFacilitiesRiskApproval"
                                           :InputData="InputData"></equipmentFacilitiesRiskApproval>
        </div>
        <div v-else-if="modaleshow==2">
          <workProcessRiskApproval ref="workProcessRiskApproval"
                                   :InputData="InputData"></workProcessRiskApproval>
        </div>
        <div v-else-if="modaleshow==3">
          <personnelJobRiskApproval ref="personnelJobRiskApproval"
                                    :InputData="InputData"></personnelJobRiskApproval>
        </div>
        <div v-else>
          <environmentalRiskApproval ref="environmentalRiskApproval"
                                     :InputData="InputData"></environmentalRiskApproval>
        </div>
        <!-- <Row type="flex" justify="space-around" class="code-row-bg">
             <Col span="23">
                 <FormItem>
                     <Button class='ivu-btn-save' @click="model1=false">关闭</Button>
                 </FormItem>
             </Col>
         </Row>-->
      </Form>
      <div slot="footer">
        <!--<Button class='ivu-btn-save'  @click="submit('InputData')">确定</Button>-->
        <Button class='ivu-btn-save' @click="model1=false">关闭</Button>
      </div>
    </Modal>
  </Layout>
</template>
<script>
import {Api} from '../../../../api/index.js'
import {formatDate} from '@/tools/index'
import {sessionStorage} from '../../../../common/cacheUtils.js';
import equipmentFacilitiesRiskApproval from '../riskApproval/equipmentFacilitiesRiskApproval.vue'
import personnelJobRiskApproval from '../riskApproval/personnelJobRiskApproval.vue'
import workProcessRiskApproval from '../riskApproval/workProcessRiskApproval.vue'
import environmentalRiskApproval from '../riskApproval/environmentalRiskApproval.vue'

export default {
  components: {
    equipmentFacilitiesRiskApproval,
    environmentalRiskApproval,
    workProcessRiskApproval,
    personnelJobRiskApproval
  },
  name: "riskBase",//风险库
  data() {
    return {
      switchFlag: false,
      loading: false,
      tableHeight: '',
      rikDiscernList: [],
      buttonLoading: false,
      riskTypeArr: [],
      rikRankList: ["重大", "较大", "一般", "低"],
      rikRanks: [],
      pageSizeArray: [10, 20, 50, 100, 200],
      reportSelectAll: [],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      dataTable: [],
      columns: [

        {
          title: "序号",
          minWidth: 80,
          align: "center",
          fixed: 'left',
          render: (h, params) => {
            return h('span', params.index + (this.pagedata.currentPage - 1) * this.pagedata.pageSize + 1);
          }
        },
        {
          width: 200,
          minWidth: 150,
          title: '一级风险单元',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.riskUnitName)
          }
        },
        {
          width: 200,
          minWidth: 150,
          title: '二级风险单元',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.riskUnit2)
          }
        },
        {
          width: 200,
          minWidth: 150,
          title: '三级风险单元',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.riskUnit3)
          }
        }, {
          width: 200,
          minWidth: 150,
          title: '四级风险单元',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.riskUnit4)
          }
        }, {//设备
          width: 200,
          minWidth: 150,
          title: '设备设施名称',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.equipmentName)
          }
        }, {
          width: 200,
          minWidth: 150,
          title: '子系统单元或重要元器件',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.subEqName)
          }
        },//设备
        {
          width: 200,
          minWidth: 150,
          title: '人员岗位',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.personnelPosition)
          }
        },
        {
          width: 200,
          minWidth: 150,
          title: '作业内容',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.workContent)
          }
        },
        {
          width: 150,
          title: '风险类别',
          align: 'center',
          key: 'riskTypeName',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.riskTypeName)
          }
        },
        {
          width: 150,
          title: '风险识别维度',
          align: 'center',
          key: 'rikDiscernName',
          render: (h, params) => {
            return h('span', params.row.saRiskInfo.rikDiscernName)
          }
        },
        {
          width: 150,
          title: '风险等级',
          align: 'center',
          key: 'rikRankName',
        },
        {
          width: 150,
          title: '风险警示色',
          align: 'center',
          key: 'rikColor',
          /* render: (h, params) => {
               // 需要延迟处理，否则颜色无法赋值
               setTimeout(() => {
                   let dom = document.getElementsByClassName(`${params.row.cellClassName.rikColor}`)
                   dom[0].style.backgroundColor = `${params.row.cellClassName.rikColor}`
               }, 100)
               return h('div', {
                   style: {
                       color: 'black'
                   }
               }, params.row.rikColor)
           }*/
        },
        {
          width: 150,
          title: '风险防范措施',
          align: 'center',
          key: 'manageMeasure', ellipsis: 'true',
          render: (h, params) => {
            return h('span', params.row.saRiskManage.manageMeasure)
          }
        },
        {
          width: 150,
          title: '应急措施', ellipsis: 'true',
          align: 'center',
          key: 'emerMearsure',
          render: (h, params) => {
            return h('span', params.row.saRiskManage.emerMearsure)
          }
        },
        {
          width: 150,
          title: '责任部门',
          align: 'center',
          key: 'dutyOrgName',
          render: (h, params) => {
            return h('span', params.row.saRiskManage.dutyOrgName)
          }
        },
        {
          width: 150,
          title: '责任人',
          align: 'center',
          key: 'dutyPersonName',
          render: (h, params) => {
            return h('span', params.row.saRiskManage.dutyPersonName)
          }
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          width: 140,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('A', {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  fontSize: '14px',
                  // marginLeft:'8px'
                },
                on: {
                  click: () => {
                    this.InputData = params.row;
                    let recordeTime = new Date(params.row.saRiskManage.recordeTime)
                    this.InputData.saRiskManage.recordeTime = recordeTime.getFullYear() + '-' + (recordeTime.getMonth() + 1) + '-' + recordeTime.getDate()
                    this.model1 = true;
                  }
                }
              }, '详情'),
            ]);
          }
        }
      ],
      loadingDownload: false,
      add: false,
      model1: false,
      InputData: {
        saRiskInfo: {},
        saRiskAssess: {},
        saRiskManage: {},
        saRiskAduitTransfer: {}
      },
      saRiskAduitTransfer: {},
      form1: {
        hazardFactor: '',
        rikRankId: '',
      },
      modaleshow: 1,
    }
  },
  computed: {
    submitDate() {
      return formatDate(this.form1.date, "yyyy");
    },
    columns1() {
      const columns = [...this.columns];
      const modaleshow = this.modaleshow
      const columns1 = []
      columns.forEach(item => {
        if (modaleshow == 1) {
          if (item.title != '作业内容' && item.title != '人员岗位') {
            columns1.push(item)
          }
        } else if (modaleshow == 2) {
          if (item.title != '设备设施名称' && item.title != '人员岗位' && item.title != '子系统单元或重要元器件') {
            columns1.push(item)
          }
        } else if (modaleshow == 3) {
          if (item.title != '设备设施名称' && item.title != '作业内容' && item.title != '子系统单元或重要元器件') {
            columns1.push(item)
          }
        } else {
          if (item.title != '设备设施名称' && item.title != '作业内容' && item.title != '人员岗位' && item.title != '子系统单元或重要元器件') {
            columns1.push(item)
          }
        }
      })
      return columns1
    },
  },
  mounted() {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 145;
    this.query()
  },
  watch: {
    "model1": function (qw, er) {
      if (qw && this.model1) {

      } else {
        this.InputData = {
          saRiskInfo: {},
          saRiskAssess: {},
          saRiskManage: {},
          saRiskAduitTransfer: {}
        }
        this.query()
      }
    },
  },
  methods: {
    reportSelect(select) {
      this.reportSelectAll = select
      console.log(select)
    },
    reporting() {
      this.$Modal.confirm({
        title: '提示',
        content: '<p>确定将选中风险从风险库中退回？</p>',
        onOk: () => {
          this.buttonLoading = true
          let map = {
            assessList: [],
            transferList: [],
          }
          this.reportSelectAll.forEach(item => {
            map.assessList.push(item.assessId)
            map.transferList.push(item.saRiskAduitTransfer.transferId)
          })
          let url = Api.deleteLibrary;
          this.$http.post(url, map).then((res) => {
            this.$Message.success('操作成功');
            this.query()
            this.reportSelectAll = []
            this.buttonLoading = false
          }).catch(e => {
            this.buttonLoading = false
            this.$Message.error("操作失败")
          })
        },
        onCancel: () => {
        }
      });
    },
    downloadFile() {
      let url = ''
      let _this = this
      if (this.modaleshow == 1) {
        url = Api.equipmentFacilitiesRiskApprovalDownload
      } else if (this.modaleshow == 2) {
        url = Api.workProcessRiskApprovalDownload

      } else if (this.modaleshow == 3) {
        url = Api.personnelJobRiskApprovalDownload

      } else if (this.modaleshow == 4) {
        url = Api.environmentalRiskApprovalDownload

      }
      let data = {}
      this.form1.rikRankId = "";
      for (let i = 0; i < this.rikRanks.length; i++) {
        this.form1.rikRankId += this.rikRanks[i] + ",";

      }
      this.form1.orgId = sessionStorage('userId').getObject('userId').companyId;
      this.form1.belongOrgName = sessionStorage('userId').getObject('userId').companyName
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      this.loadingDownload = true;
      this.$http.get(url, {
        params: data,
        responseType: 'blob'      //告诉服务器我们需要的响应格式
      }).then((res) => {
        this.loadingDownload = false;
        const aLink = document.createElement("a");
        let blob = new Blob([res.data], {
          type: res.bodyBlob.type      //将会被放入到blob中的数组内容的MIME类型
        });
        aLink.href = URL.createObjectURL(blob)
        if (this.modaleshow == 1) {
          aLink.download = "安全风险库(设备设施风险)(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题
        } else if (this.modaleshow == 2) {
          aLink.download = "安全风险库(作业流程风险)(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题

        } else if (this.modaleshow == 3) {
          aLink.download = "安全风险库(人员岗位风险)(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题

        } else if (this.modaleshow == 4) {
          aLink.download = "安全风险库(环境氛围风险)(" + formatDate(new Date(), "yyyy-MM-dd") + ").xlsx" //标题

        }
        aLink.click()
        document.body.appendChild(aLink)
      }).catch(e => {
        this.$Message.error("导出失败")
        this.loadingDownload = false;
      })
    },
    lowerStep(name) {
      this.modaleshow = name
      this.query()
    },
    query() {
      let url = ''
      let _this = this
      if (this.modaleshow == 1) {
        url = Api.equipmentFacilitiesRiskApprovalList
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10005", function (result) {
          _this.riskTypeArr = result;
        });
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10010", function (result) {
          _this.rikDiscernList = result;
        });
      } else if (this.modaleshow == 2) {
        url = Api.workProcessRiskApprovalList
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10007", function (result) {
          _this.riskTypeArr = result;
        });
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10011", function (result) {
          _this.rikDiscernList = result;
        });
      } else if (this.modaleshow == 3) {
        url = Api.personnelJobRiskApprovalList
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10008", function (result) {
          _this.riskTypeArr = result;
        });
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10012", function (result) {
          _this.rikDiscernList = result;
        });
      } else if (this.modaleshow == 4) {
        url = Api.environmentalRiskApprovalList
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10009", function (result) {
          _this.riskTypeArr = result;
        });
        this.gDic(Api.queryCodeDetailBySortId + "/risk-10013", function (result) {
          _this.rikDiscernList = result;
        });
      }
      let data = {
        startPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
      }
      if (this.form1.date) {
        this.form1.year = new Date(this.form1.date).getFullYear();
      } else {
        this.form1.date = new Date();
        this.form1.year = new Date().getFullYear();
      }
      this.form1.rikRankId = "";
      for (let i = 0; i < this.rikRanks.length; i++) {
        this.form1.rikRankId += this.rikRanks[i] + ",";

      }
      this.form1.orgId = sessionStorage('userId').getObject('userId').companyId
      this.form1.belongOrgName = sessionStorage('userId').getObject('userId').companyName
      data = Object.assign(data, JSON.parse(JSON.stringify(this.form1)));
      this.loading = true
      this.$http.get(url, {params: data}).then((res) => {
        console.log(res.data);
        res.data.data.data.forEach(item => {
          const sty = item.rikColor == '红' ? 'table-info-cell-red' : item.rikColor == '橙' ? 'table-info-cell-orage' : item.rikColor == '黄' ? 'table-info-cell-yellow' : item.rikColor == '蓝' ? 'table-info-cell-blue' : ''
          item.cellClassName = {rikColor: sty}
        })
        this.dataTable = res.data.data.data;
        this.pagedata.total = res.data.data.totalSize;
        // this.columns1()

        this.loading = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
        this.loading = false;
      })
    },
    reset() {
      this.form1 = {}
      this.rikRanks = [];
      this.pagedata.currentPage = 1
      this.query()
    },
    switchQuery(flag) {
      this.switchFlag = flag;
      if (!this.switchFlag) {
        this.tableHeight = this.tableHeight + 88;
      } else {
        this.tableHeight = this.tableHeight - 88;
      }
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },

  }
}
</script>


<style scoped>
@import '../../../../index.css';
</style>
